//
//  LImageView.m
//  LGQImageView
//
//  Created by LGQ on 2020/7/28.
//  Copyright © 2020 上海创酷信息科技有限公司. All rights reserved.
//

#import "LImageView.h"

#import "MagnifierView.h"

@interface LImageView ()<UIScrollViewDelegate>

/// 主view - 用于图片缩放
@property (nonatomic, strong) UIScrollView *scrollView;

/// 左上角度拖动区域
@property (nonatomic, strong) AreaView *topLeftAreaView;
/// 右上角拖动区域
@property (nonatomic, strong) AreaView *topRightAreaView;
/// 上边中间拖动区域
@property (nonatomic, strong) AreaView *topCenterAreaView;
/// 左边中间拖动区域
@property (nonatomic, strong) AreaView *leftCenterAreaView;
/// 右边中间拖动区域
@property (nonatomic, strong) AreaView *rightCenterAreaView;
/// 底部中间拖动区域
@property (nonatomic, strong) AreaView *bottomCenterAreaView;
/// 左下角拖动区域
@property (nonatomic, strong) AreaView *bottomLeftAreaView;
/// 右下角拖动区域
@property (nonatomic, strong) AreaView *bottomRightAreaView;
/// 蒙层
@property (nonatomic, strong) UIView *maskView;
/// 边界线
@property (nonatomic, strong) CAShapeLayer *lineLayer;
/// 裁剪区域拖动点所在view
@property (nonatomic, strong) UIView *areaView;

/// <#Description#>
@property (nonatomic, assign) CGPoint currentPoint;

/// <#Description#>
@property (nonatomic, assign) CGFloat currentScale;
/// <#Description#>
@property (nonatomic, assign) CGFloat lastScale;
/// <#Description#>
@property (nonatomic, assign) CGFloat areaWidth;

/// <#Description#>
@property (nonatomic, strong) MagnifierView *magnifierView;

@end

/// 可拖动点的宽高
static CGFloat const areaPointWH = 40;

#define kView_W(view) CGRectGetWidth(view.frame)
#define kView_H(view) CGRectGetHeight(view.frame)
#define kView_MaxX(view) CGRectGetMaxX(view.frame)
#define kView_MaxY(view) CGRectGetMaxY(view.frame)
#define kView_X(view) CGRectGetMinX(view.frame)
#define kView_Y(view) CGRectGetMinY(view.frame)

@implementation LImageView

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        [self addViews];
    }
    
    return self;
}

/// xib创建
- (void)awakeFromNib {
    [super awakeFromNib];
    
    [self addViews];
}

/// 添加控件
- (void)addViews {
    
    self.currentScale = self.lastScale = 1;
    
    self.minClipWidthAndHeight = 100;
    
    [self addSubview:self.scrollView];
    [self.scrollView addSubview:self.imageView];
    [self.scrollView addSubview:self.maskView];
    [self.scrollView addSubview:self.areaView];
    [self.areaView.layer addSublayer:self.lineLayer];
    [self.areaView addSubview:self.topLeftAreaView];
    [self.areaView addSubview:self.topRightAreaView];
    [self.areaView addSubview:self.bottomLeftAreaView];
    [self.areaView addSubview:self.bottomRightAreaView];
    [self.areaView addSubview:self.topCenterAreaView];
    [self.areaView addSubview:self.leftCenterAreaView];
    [self.areaView addSubview:self.rightCenterAreaView];
    [self.areaView addSubview:self.bottomCenterAreaView];
}

/// 设置图片
/// @param originImage 原图
- (void)setOriginImage:(UIImage *)originImage {
    _originImage = originImage;
    
    if (!originImage) {
        return;
    }
    
    CGFloat scale = originImage.size.height/originImage.size.width;
    CGFloat imageViewWidth = self.bounds.size.width;
    CGFloat imageViewHeight = imageViewWidth * scale;
    
    // 如果高度超出父视图高度，则高度为父视图高度，并等比缩放宽度
    if (imageViewHeight > self.bounds.size.height) {
        
        scale = self.bounds.size.height/imageViewHeight;
        imageViewHeight = self.bounds.size.height;
        
        imageViewWidth = imageViewWidth*scale;
    }
    
    self.scrollView.contentSize = CGSizeZero;
    
    self.lastScale = 1;
    self.currentScale = 1;
    [self.scrollView setZoomScale:1];
    
    self.scrollView.frame = CGRectMake((self.bounds.size.width - imageViewWidth - 20)/2, (self.bounds.size.height - imageViewHeight - 20)/2, imageViewWidth+20, imageViewHeight+20);
    
    self.imageView.frame =
    self.maskView.frame =
    self.areaView.frame = CGRectMake(10, 10, imageViewWidth, imageViewHeight);
    
    self.imageView.image = originImage;
    
    // 最小高度不能低于100 - 2个按钮的宽度 + 2*10的间距
    if (self.minClipWidthAndHeight < 100) {

        self.minClipWidthAndHeight = 100;
    }

    if (self.minClipWidthAndHeight > kView_W(self.imageView) ||
        self.minClipWidthAndHeight > kView_H(self.imageView)) {
        
        self.minClipWidthAndHeight = MIN(kView_W(self.imageView), kView_H(self.imageView));
    }
    
    self.imageView.userInteractionEnabled = self.areaView.userInteractionEnabled = YES;
//
//    [self resetAreaViewRect];
}

- (void)setScaleForScrollView:(CGFloat)scale {
    
    self.currentScale = self.lastScale = scale;
    
    [self.scrollView setZoomScale:scale];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.scrollView setContentSize:CGSizeMake(kView_W(self.areaView) + 20, kView_H(self.areaView) + 20)];
    });

    if (scale > 1) {

        self.areaView.userInteractionEnabled = self.imageView.userInteractionEnabled = NO;
    } else {

        self.areaView.userInteractionEnabled = self.imageView.userInteractionEnabled = YES;
    }
}

/** 设置拖动点坐标
    
    将拖动点置于图片的四个顶点和四个边的中点
 */
- (void)resetAreaViewRect {
    
    self.topLeftAreaView.center = CGPointZero;
    self.topLeftAreaView.hidden = NO;
    
    self.topRightAreaView.center = CGPointMake(kView_W(self.areaView), 0);
    self.topRightAreaView.hidden = NO;
    
    self.bottomLeftAreaView.center = CGPointMake(0, kView_H(self.areaView));
    self.bottomLeftAreaView.hidden = NO;
    
    self.bottomRightAreaView.center = CGPointMake(kView_W(self.areaView), kView_H(self.areaView));
    self.bottomRightAreaView.hidden = NO;
    
    self.topCenterAreaView.center = CGPointMake(self.areaView.center.x, 0);
    self.topCenterAreaView.hidden = NO;
    
    self.leftCenterAreaView.center = CGPointMake(0, kView_H(self.areaView)/2);
    self.leftCenterAreaView.hidden = NO;
    
    self.rightCenterAreaView.center = CGPointMake(kView_W(self.areaView), kView_H(self.areaView)/2);
    self.rightCenterAreaView.hidden = NO;
    
    self.bottomCenterAreaView.center = CGPointMake(kView_W(self.areaView)/2, kView_H(self.areaView));
    self.bottomCenterAreaView.hidden = NO;
    
    [self resetMaskPath];
}

/// 设置蒙层路径
- (void)resetMaskPath {
    
    CAShapeLayer *maskLayer = (CAShapeLayer *)self.maskView.layer.mask;
    if (!maskLayer) {
        
        maskLayer = [CAShapeLayer layer];
        self.maskView.layer.mask = maskLayer;
    }
    
    // 将8个点连接起来
    UIBezierPath *clearPath = [UIBezierPath bezierPath];
    [clearPath moveToPoint:self.topLeftAreaView.center];
    [clearPath addLineToPoint:self.topCenterAreaView.center];
    [clearPath addLineToPoint:self.topRightAreaView.center];
    [clearPath addLineToPoint:self.rightCenterAreaView.center];
    [clearPath addLineToPoint:self.bottomRightAreaView.center];
    [clearPath addLineToPoint:self.bottomCenterAreaView.center];
    [clearPath addLineToPoint:self.bottomLeftAreaView.center];
    [clearPath addLineToPoint:self.leftCenterAreaView.center];
    [clearPath closePath];
    
    UIBezierPath *maskPath = [[UIBezierPath bezierPathWithRect:self.maskView.bounds] bezierPathByReversingPath];
    [maskPath appendPath:clearPath];
    
    maskLayer.path = maskPath.CGPath;
    
    self.lineLayer.path = clearPath.CGPath;
}

/// 拖动顶点裁剪范围
- (void)movePoint:(UIPanGestureRecognizer *)pan {
    
    AreaView *view = (AreaView *)pan.view;
    
    if (pan.state == UIGestureRecognizerStateBegan) {
        
        [self.magnifierView showMagnifierView];
        
        view.centerLayer.fillColor = [UIColor clearColor].CGColor;
        
    } else if (pan.state == UIGestureRecognizerStateChanged) {
        
        CGPoint location = [pan locationInView:self.areaView];
        
        CGFloat x = location.x;
        CGFloat y = location.y;
        // 将裁剪范围限制在图片范围内
        if (!CGRectContainsPoint(self.areaView.bounds, location)) {
            
            if (location.x < 0) {
                
                x = 0;
            }
            
            if (location.x > kView_W(self.areaView)) {
                
                x = kView_W(self.areaView);
            }
            
            if (location.y < 0) {
                
                y = 0;
            }
            
            if (y > kView_H(self.areaView)) {
                
                y = kView_H(self.areaView);
            }
        }
        
        CGFloat centerArea1X = 0.0,centerArea1Y = 0.0,centerArea2X = 0.0,centerArea2Y = 0.0;
        
        CGFloat areaWidht = kView_W(self.areaView);
        CGFloat areaHeight = kView_H(self.areaView);
        
        if (view == self.topLeftAreaView) {
            
            // 设置左右间距
            CGFloat minMarginX = MIN(MIN(self.topRightAreaView.center.x, self.rightCenterAreaView.center.x), self.bottomRightAreaView.center.x);
            
            CGFloat minMarginY = MIN(MIN(self.bottomLeftAreaView.center.y, self.bottomCenterAreaView.center.y), self.bottomRightAreaView.center.y);
            
            if (x >= minMarginX - self.minClipWidthAndHeight) {
                
                x = minMarginX - self.minClipWidthAndHeight;
            }
            
            if (y >= minMarginY - self.minClipWidthAndHeight) {
                
                y = minMarginY - self.minClipWidthAndHeight;
            }
            
//            centerArea1X = (areaWidht - x - (areaWidht - self.topRightAreaView.center.x))/2 + x;
            
            centerArea1X = (self.topRightAreaView.center.x - x)/2 + x;
            centerArea1Y = (fabs(self.topRightAreaView.center.y - y)/2 + MIN(y, self.topRightAreaView.center.y));
//            centerArea1Y = (areaHeight - y - (areaHeight - self.topRightAreaView.center.y))/2 + y;
            
            centerArea2X = (fabs(x - self.bottomLeftAreaView.center.x))/2 + MIN(x, self.bottomLeftAreaView.center.x);;
            centerArea2Y = (areaHeight - y - (areaHeight - self.bottomLeftAreaView.center.y))/2 + y;
            
        } else if (view == self.bottomLeftAreaView) {
            
            CGFloat minMarginX = MIN(MIN(self.topRightAreaView.center.x, self.rightCenterAreaView.center.x), self.bottomRightAreaView.center.x);
            
            CGFloat minMarginY = MAX(MAX(self.topLeftAreaView.center.y, self.topCenterAreaView.center.y), self.topRightAreaView.center.y);
            
            if (x >= minMarginX - self.minClipWidthAndHeight) {
                
                x = minMarginX - self.minClipWidthAndHeight;
            }
            
            if (y <= minMarginY + self.minClipWidthAndHeight) {
                
                y = minMarginY + self.minClipWidthAndHeight;
            }
            
            centerArea1X = (areaWidht - x - (areaWidht - self.bottomRightAreaView.center.x))/2 + x;
            centerArea1Y = (areaHeight - y - (areaHeight - self.bottomRightAreaView.center.y))/2 + y;
            
            centerArea2X = (fabs(x - self.topLeftAreaView.center.x))/2 + MIN(x, self.topLeftAreaView.center.x);
            centerArea2Y = (areaHeight - y - (areaHeight - self.topLeftAreaView.center.y))/2 + y;
            
        } else if (view == self.topRightAreaView) {
            
            CGFloat maxMarginX = MAX(MAX(self.topLeftAreaView.center.x, self.leftCenterAreaView.center.x), self.bottomLeftAreaView.center.x);
            
            CGFloat minMarginY = MIN(MIN(self.bottomLeftAreaView.center.y, self.bottomCenterAreaView.center.y), self.bottomRightAreaView.center.y);
            
            if (x <= maxMarginX + self.minClipWidthAndHeight) {
                
                x = maxMarginX + self.minClipWidthAndHeight;
            }
            
            if (y >= minMarginY - self.minClipWidthAndHeight) {
                
                y = minMarginY - self.minClipWidthAndHeight;
            }
            
            centerArea1X = (areaWidht - self.topLeftAreaView.center.x - (areaWidht - x))/2 + self.topLeftAreaView.center.x;
            centerArea1Y = (fabs(y - self.topLeftAreaView.center.y))/2 + MIN(y, self.topLeftAreaView.center.y);
            
            centerArea2X = (fabs(x - self.bottomRightAreaView.center.x))/2 + MIN(x, self.bottomRightAreaView.center.x);
            centerArea2Y = (areaHeight - y - (areaHeight - self.bottomRightAreaView.center.y))/2 + y;
            
        } else if (view == self.bottomRightAreaView) {
            
            CGFloat maxMarginX = MAX(MAX(self.topLeftAreaView.center.x, self.leftCenterAreaView.center.x), self.bottomLeftAreaView.center.x);
            
            CGFloat minMarginY = MAX(MAX(self.topLeftAreaView.center.y, self.topCenterAreaView.center.y), self.topRightAreaView.center.y);
            
            if (x <= maxMarginX + self.minClipWidthAndHeight) {
                
                x = maxMarginX + self.minClipWidthAndHeight;
            }
            
            if (y <= minMarginY + self.minClipWidthAndHeight) {
                
                y = minMarginY + self.minClipWidthAndHeight;
            }
            
            centerArea1X = (areaWidht - self.bottomLeftAreaView.center.x - (areaWidht - x))/2 + self.bottomLeftAreaView.center.x;
            centerArea1Y = (areaHeight - y - (areaHeight - self.bottomLeftAreaView.center.y))/2 + y;
            
            centerArea2X = (fabs(x - self.topRightAreaView.center.x))/2 + MIN(x, self.topRightAreaView.center.x);
            centerArea2Y = (areaHeight - y - (areaHeight - self.topRightAreaView.center.y))/2 + y;
        }
        
        view.relationView1.center = CGPointMake(centerArea1X, centerArea1Y);
        view.relationView2.center = CGPointMake(centerArea2X, centerArea2Y);
        
        view.center = CGPointMake(x, y);
        
        CGPoint point = CGPointMake(x, y);
        CGPoint magnifierPoint = [self.areaView convertPoint:point toView:self.window];
        self.magnifierView.touchPoint = magnifierPoint;
        
        [self resetMaskPath];
    } else if (pan.state == UIGestureRecognizerStateEnded) {
        
        self.magnifierView.hidden = YES;
        self.magnifierView = nil;
        
        view.centerLayer.fillColor = [UIColor whiteColor].CGColor;
    }
}

/// 拖动中心点裁剪范围
- (void)moveCenterPoint:(UIPanGestureRecognizer *)pan {
    
    AreaView *view = (AreaView *)pan.view;
    
    if (pan.state == UIGestureRecognizerStateBegan) {
        
        self.magnifierView.hidden = NO;
        
        view.centerLayer.fillColor = [UIColor clearColor].CGColor;
        
    } else if (pan.state == UIGestureRecognizerStateChanged) {
        
        CGPoint point = [pan locationInView:self.areaView];
        
        if (view == self.leftCenterAreaView ||
            view == self.rightCenterAreaView) {
            
            CGFloat x = point.x;
            
            if (x < 0) {

                x = 0;
            }
            
            if (x > kView_W(self.areaView)) {

                x = kView_W(self.areaView);
            }
            
            CGFloat areaWidth = CGRectGetWidth(self.areaView.frame);
            
            CGPoint center = view.center;
            
            CGFloat relation1X = view.relationView1.center.x;
            CGFloat relation2X = view.relationView2.center.x;
            
            CGFloat topAreaCenterX = self.topCenterAreaView.center.x;
            CGFloat topAreaCenterY = self.topCenterAreaView.center.y;
            
            CGFloat bottomAreaCenterX = self.bottomCenterAreaView.center.x;
            CGFloat bottomAreaCenterY = self.bottomCenterAreaView.center.y;
            
            CGFloat margin = x - center.x;
            
            relation1X += margin;
            relation2X += margin;
            
            if (relation1X < 0) {
                
                relation1X = 0;
                relation2X = 2*x;
            }
            
            if (relation1X > areaWidth) {
                
                relation1X = areaWidth;
                relation2X = areaWidth - (areaWidth - x)*2;
            }
            
            if (relation2X < 0) {
                
                relation2X = 0;
                relation1X = 2*x;
            }
            
            if (relation2X > areaWidth) {
                
                relation2X = areaWidth;
                relation1X = areaWidth - (areaWidth - x)*2;
            }
            
            if (view == self.leftCenterAreaView) {
                
                CGFloat minMarginX = MIN(MIN(self.topRightAreaView.center.x, self.rightCenterAreaView.center.x), self.bottomRightAreaView.center.x);
                
                if (x >= minMarginX - self.minClipWidthAndHeight) {
                    
                    x = minMarginX - self.minClipWidthAndHeight;
                }
                
                if (relation1X >= minMarginX - self.minClipWidthAndHeight) {
                    
                    relation1X = minMarginX - self.minClipWidthAndHeight;
                    
                    relation2X = x - (relation1X - x);
                }
                
                if (relation2X >= minMarginX - self.minClipWidthAndHeight) {
                    
                    relation2X = minMarginX - self.minClipWidthAndHeight;
                    
                    relation1X = x - (relation2X - x);
                }
            } else {
                
                CGFloat maxMarginX = MAX(MAX(self.topLeftAreaView.center.x, self.leftCenterAreaView.center.x), self.bottomLeftAreaView.center.x);
                
                if (x <= maxMarginX + self.minClipWidthAndHeight) {
                    
                    x = maxMarginX + self.minClipWidthAndHeight;
                }
                
                if (relation1X <= maxMarginX + self.minClipWidthAndHeight) {
                    
                    relation1X = maxMarginX + self.minClipWidthAndHeight;
                    
                    relation2X = x + (x - relation1X);
                }
                
                if (relation2X <= maxMarginX + self.minClipWidthAndHeight) {
                    
                    relation2X = maxMarginX + self.minClipWidthAndHeight;
                    
                    relation1X = x + (x - relation2X);
                }
            }
            
            view.center = CGPointMake(x, center.y);
            view.relationView1.center = CGPointMake(relation1X, view.relationView1.center.y);
            view.relationView2.center = CGPointMake(relation2X, view.relationView2.center.y);
            
            topAreaCenterX = (areaWidth - self.topLeftAreaView.center.x - (areaWidth - self.topRightAreaView.center.x))/2 + self.topLeftAreaView.center.x;
            bottomAreaCenterX = (areaWidth - self.bottomLeftAreaView.center.x - (areaWidth - self.bottomRightAreaView.center.x))/2 + self.bottomLeftAreaView.center.x;
            
            self.topCenterAreaView.center = CGPointMake(topAreaCenterX, topAreaCenterY);
            self.bottomCenterAreaView.center = CGPointMake(bottomAreaCenterX, bottomAreaCenterY);
            
            
        } else {

            CGFloat y = point.y;
            
            if (y < 0) {
                
                y = 0;
            }
            
            if (y > kView_H(self.areaView)) {
                
                y = kView_H(self.areaView);
            }
            
            CGFloat areaHeight = kView_H(self.areaView);
            
            CGPoint center = view.center;
            
            CGFloat relation1Y = view.relationView1.center.y;
            CGFloat relation2Y = view.relationView2.center.y;
            
            CGFloat leftAreaCenterX = self.leftCenterAreaView.center.x;
            CGFloat leftAreaCenterY = self.leftCenterAreaView.center.y;
            
            CGFloat rightAreaCenterX = self.rightCenterAreaView.center.x;
            CGFloat rightAreaCenterY = self.rightCenterAreaView.center.y;
            
            CGFloat margin = y - center.y;
            
            relation1Y += margin;
            relation2Y += margin;
            
            if (relation1Y < 0) {
                
                relation1Y = 0;
                relation2Y = 2*y;
            }
            
            if (relation1Y > areaHeight) {
                
                relation1Y = areaHeight;
                relation2Y = areaHeight - (areaHeight - y)*2;
            }
            
            if (relation2Y < 0) {
                
                relation2Y = 0;
                relation1Y = 2*y;
            }
            
            if (relation2Y > areaHeight) {
                
                relation2Y = areaHeight;
                relation1Y = areaHeight - (areaHeight - y)*2;
            }
            
            if (view == self.topCenterAreaView) {

                CGFloat minMarginY = MIN(MIN(self.bottomLeftAreaView.center.y, self.bottomCenterAreaView.center.y), self.bottomRightAreaView.center.y);
                
                if (y >= minMarginY - self.minClipWidthAndHeight) {
                    
                    y = minMarginY - self.minClipWidthAndHeight;
                }
                
                if (relation1Y >= minMarginY - self.minClipWidthAndHeight) {
                    
                    relation1Y = minMarginY - self.minClipWidthAndHeight;
                    
                    relation2Y = y - (relation1Y - y);
                }
                
                if (relation2Y >= minMarginY - self.minClipWidthAndHeight) {
                    
                    relation2Y = minMarginY - self.minClipWidthAndHeight;
                    
                    relation1Y = y - (relation2Y - y);
                }
            } else {

                CGFloat maxMarginY = MAX(MAX(self.topLeftAreaView.center.y, self.topCenterAreaView.center.y), self.topRightAreaView.center.y);
                
                if (y <= maxMarginY + self.minClipWidthAndHeight) {
                    
                    y = maxMarginY + self.minClipWidthAndHeight;
                }
                
                if (relation1Y <= maxMarginY + self.minClipWidthAndHeight) {
                    
                    relation1Y = maxMarginY + self.minClipWidthAndHeight;
                    
                    relation2Y = y + (y - relation1Y);
                }
                
                if (relation2Y <= maxMarginY + self.minClipWidthAndHeight) {
                    
                    relation2Y = maxMarginY + self.minClipWidthAndHeight;
                    
                    relation1Y = y + (y - relation2Y);
                }
            }
            
            view.center = CGPointMake(center.x, y);
            view.relationView1.center = CGPointMake(view.relationView1.center.x, relation1Y);
            view.relationView2.center = CGPointMake(view.relationView2.center.x, relation2Y);
            
            
            leftAreaCenterY = (areaHeight - self.topLeftAreaView.center.y - (areaHeight - self.bottomLeftAreaView.center.y))/2 + self.topLeftAreaView.center.y;
            rightAreaCenterY = (areaHeight - self.topRightAreaView.center.y - (areaHeight - self.bottomRightAreaView.center.y))/2 + self.topRightAreaView.center.y;
            
            self.leftCenterAreaView.center = CGPointMake(leftAreaCenterX, leftAreaCenterY);
            self.rightCenterAreaView.center = CGPointMake(rightAreaCenterX, rightAreaCenterY);
        }
        
        [self resetMaskPath];
        
        CGPoint touchPoint = view.center;
        CGPoint magnifierPoint = [self.areaView convertPoint:touchPoint toView:self.window];
        self.magnifierView.touchPoint = magnifierPoint;
        
    } else if (pan.state == UIGestureRecognizerStateEnded) {
        
        self.magnifierView.hidden = YES;
        self.magnifierView = nil;
        
        view.centerLayer.fillColor = [UIColor whiteColor].CGColor;
    }
}

- (void)moveArea:(UIPanGestureRecognizer *)pan {
    
    CGPoint point = [pan locationInView:self.areaView];
    
    if (pan.state == UIGestureRecognizerStateBegan) {
        
        self.currentPoint = [pan locationInView:self.areaView];
    } else if (pan.state == UIGestureRecognizerStateChanged) {
        
        if (CGPathContainsPoint(self.lineLayer.path, nil, point, NO)) {
            
            [self moveAreaWithPoint:point];
        }
    } else if (pan.state == UIGestureRecognizerStateEnded) {
        
        [self checkPointInAreaRect];
    }
}

- (void)moveAreaWithPoint:(CGPoint)point {
    
    CGFloat xMove = 0, yMove = 0;
    
    xMove = point.x - self.currentPoint.x;
    yMove = point.y - self.currentPoint.y;
    
    if (xMove > 0) {// 向右移动
        
        if (MAX(MAX(self.topRightAreaView.center.x, self.rightCenterAreaView.center.x), self.bottomRightAreaView.center.x) >= kView_W(self.areaView)) {
            
            xMove = 0;
        }
    } else if (xMove <= 0) {// 向左移动
        
        if (MIN(MIN(self.topLeftAreaView.center.x, self.leftCenterAreaView.center.x), self.bottomLeftAreaView.center.x) <= 0) {
            
            xMove = 0;
        }
    }
    
    if (yMove > 0) {// 向下移动
        
        if (MAX(MAX(self.bottomLeftAreaView.center.y, self.bottomCenterAreaView.center.y), self.bottomRightAreaView.center.y) >= kView_H(self.areaView)) {
            
            yMove = 0;
        }
    } else if (yMove <= 0) {// 向上移动
        
        if (MIN(MIN(self.topLeftAreaView.center.y, self.topCenterAreaView.center.y), self.topRightAreaView.center.y) <= 0) {
            
            yMove = 0;
        }
    }
    
    [self moveAllAreaViewPoint:CGPointMake(xMove, yMove)];
    
    self.currentPoint = point;
}

/// 检查锚点边界是否超出区域
- (void)checkPointInAreaRect {
    
    CGFloat moveX = 0, moveY = 0;
    
    if (MIN(self.topLeftAreaView.center.x, self.bottomLeftAreaView.center.x) < 0) {
        
        moveX = fabs(MIN(self.topLeftAreaView.center.x, self.bottomLeftAreaView.center.x));
    } else if (MAX(self.topRightAreaView.center.x, self.bottomRightAreaView.center.x) > kView_W(self.areaView)) {
        
        moveX = kView_W(self.areaView) - MAX(self.topRightAreaView.center.x, self.bottomRightAreaView.center.x);
    }
    
    if (MIN(self.topLeftAreaView.center.y, self.topRightAreaView.center.y) < 0) {
        
        moveY = fabs(MIN(self.topLeftAreaView.center.y, self.topRightAreaView.center.y));
    } else if (MAX(self.bottomLeftAreaView.center.y, self.bottomRightAreaView.center.y) > kView_H(self.areaView)) {
        
        moveY = kView_H(self.areaView) - MAX(self.bottomLeftAreaView.center.y, self.bottomRightAreaView.center.y);
    }
    
    if (moveX != 0 || moveY != 0) {
        
        [self moveAllAreaViewPoint:CGPointMake(moveX, moveY)];
    }
}

/// 移动所有锚点
/// @param point 需要移动的x轴和y轴的距离
- (void)moveAllAreaViewPoint:(CGPoint)point {
    
    for (UIView *view in self.areaView.subviews) {
        
        if ([view isKindOfClass:[AreaView class]]) {
            
            CGFloat x = view.center.x + point.x;
            CGFloat y = view.center.y + point.y;
            
            view.center = CGPointMake(x, y);
        }
    }
    
    [self resetMaskPath];
}

- (void)setPointColor:(UIColor *)pointColor {
    _pointColor = pointColor;
    
    for (UIView *view in self.areaView.subviews) {
        
        if ([view isKindOfClass:[AreaView class]]) {
            
            AreaView *areaView = (AreaView *)view;
            areaView.centerLayer.strokeColor = pointColor.CGColor;
        }
    }
}

- (void)setLineColor:(UIColor *)lineColor {
    _lineColor = lineColor;
    
    self.lineLayer.strokeColor = lineColor.CGColor;
}

/// 获取裁剪后的图片
- (UIImage *)currentImage {
    
    CGFloat hScale = self.originImage.size.width/kView_W(self.imageView);
    CGFloat vScale = self.originImage.size.height/kView_H(self.imageView);
    
    /*
     将imageview的路径转换为图片的路径
     这样可以使图片在切割时不用缩放，防止图片失真
     */
    UIBezierPath *path = [UIBezierPath bezierPath];
    
    [path moveToPoint:CGPointMake(self.topLeftAreaView.center.x*hScale, self.topLeftAreaView.center.y*vScale)];
    [path addLineToPoint:CGPointMake(self.topCenterAreaView.center.x*hScale, self.topCenterAreaView.center.y*vScale)];
    [path addLineToPoint:CGPointMake(self.topRightAreaView.center.x*hScale, self.topRightAreaView.center.y*vScale)];
    [path addLineToPoint:CGPointMake(self.rightCenterAreaView.center.x*hScale, self.rightCenterAreaView.center.y*vScale)];
    [path addLineToPoint:CGPointMake(self.bottomRightAreaView.center.x*hScale, self.bottomRightAreaView.center.y*vScale)];
    [path addLineToPoint:CGPointMake(self.bottomCenterAreaView.center.x*hScale, self.bottomCenterAreaView.center.y*vScale)];
    [path addLineToPoint:CGPointMake(self.bottomLeftAreaView.center.x*hScale, self.bottomLeftAreaView.center.y*vScale)];
    [path addLineToPoint:CGPointMake(self.leftCenterAreaView.center.x*hScale, self.leftCenterAreaView.center.y*vScale)];
    [path closePath];
    
    CGFloat x = 0,y = 0,width = 0,height = 0;
    
    x = hScale *MIN(self.topLeftAreaView.center.x, self.topRightAreaView.center.x);
    y = vScale *MIN(self.topLeftAreaView.center.y, self.topRightAreaView.center.y);
    width = hScale *MAX(self.topRightAreaView.center.x, self.bottomRightAreaView.center.x);
    height = vScale *MAX(self.bottomLeftAreaView.center.y, self.bottomRightAreaView.center.y);
    
    CGRect rect = CGRectMake(x, y, width, height);
    
    return [self.originImage clipWithPath:[path copy] rect:rect];
}

/// 获取当前裁剪的坐标点
- (NSArray *)getCurrentPathPoints {
    
    NSString *leftTopCenter = NSStringFromCGPoint(self.topLeftAreaView.center);
    NSString *topCenterCenter = NSStringFromCGPoint(self.topCenterAreaView.center);
    NSString *topRightCenter = NSStringFromCGPoint(self.topRightAreaView.center);
    NSString *rightCenterCenter = NSStringFromCGPoint(self.rightCenterAreaView.center);
    NSString *bottomRightCenter = NSStringFromCGPoint(self.bottomRightAreaView.center);
    NSString *bottomCenterCenter = NSStringFromCGPoint(self.bottomCenterAreaView.center);
    NSString *bottomLeftCenter = NSStringFromCGPoint(self.bottomLeftAreaView.center);
    NSString *leftCenterCenter = NSStringFromCGPoint(self.leftCenterAreaView.center);
    
    return @[leftTopCenter,
                        topCenterCenter,
                        topRightCenter,
                        rightCenterCenter,
                        bottomRightCenter,
                        bottomCenterCenter,
                        bottomLeftCenter,
                        leftCenterCenter];
}

/// 设置裁剪区域
/// @param points 8个顶点的坐标
- (void)setAreaPathWithPoints:(NSArray *)points {
    
    if (points.count > 0) {
        
        self.topLeftAreaView.center = CGPointFromString(points[0]);
        self.topCenterAreaView.center = CGPointFromString(points[1]);
        self.topRightAreaView.center = CGPointFromString(points[2]);
        self.rightCenterAreaView.center = CGPointFromString(points[3]);
        self.bottomRightAreaView.center = CGPointFromString(points[4]);
        self.bottomCenterAreaView.center = CGPointFromString(points[5]);
        self.bottomLeftAreaView.center = CGPointFromString(points[6]);
        self.leftCenterAreaView.center = CGPointFromString(points[7]);
        
        [self resetMaskPath];
    } else {
        
        [self resetAreaViewRect];
    }
}

- (void)setAnonateAreaRect:(CGRect)rect {
    
    if (CGRectGetWidth(rect) <= 0 || CGRectGetHeight(rect) <= 0) {
        
        [self resetAreaViewRect];
        
        return;
    }
    
    CGFloat hScale = kView_H(self.imageView)/self.originImage.size.height;
    CGFloat vScale = kView_W(self.imageView)/self.originImage.size.width;
    
    CGFloat x = rect.origin.x *vScale;
    CGFloat y = rect.origin.y *hScale;
    CGFloat width = rect.size.width *vScale;
    CGFloat height = rect.size.height *hScale;
    
    CGFloat areaWidth = kView_W(self.areaView);
    CGFloat areaHeight = kView_H(self.areaView);
    
    if (x < 0) {
        x = 0;
    }
    
    if (x > areaWidth) {
        x = areaWidth - self.minClipWidthAndHeight;
    }
    
    if (y < 0) {
        y = 0;
    }
    
    if (y > areaHeight) {
        y = areaHeight - self.minClipWidthAndHeight;
    }
    
    if (width < self.minClipWidthAndHeight) {
        
        width = self.minClipWidthAndHeight;
    }
    
    if (width > areaWidth) {
        width = areaWidth;
    }
    
    if (height < self.minClipWidthAndHeight) {
        height = self.minClipWidthAndHeight;
    }
    
    if (height > areaHeight) {
        height = areaHeight;
    }
    
    CGRect r = CGRectMake(x, y, width, height);
    
    self.topLeftAreaView.center = CGPointMake(r.origin.x, r.origin.y);
    self.topLeftAreaView.hidden = NO;
    
    self.bottomLeftAreaView.center = CGPointMake(r.origin.x, CGRectGetMaxY(r));
    self.bottomLeftAreaView.hidden = NO;
    
    self.bottomRightAreaView.center = CGPointMake(CGRectGetMaxX(r), CGRectGetMaxY(r));
    self.bottomRightAreaView.hidden = NO;
    
    self.topRightAreaView.center = CGPointMake(CGRectGetMaxX(r), r.origin.y);
    self.topRightAreaView.hidden = NO;
    
    
    for (UIView *view in self.areaView.subviews) {
        
        if (view == self.topCenterAreaView ||
            view == self.leftCenterAreaView ||
            view == self.bottomCenterAreaView ||
            view == self.rightCenterAreaView) {
            
            AreaView *centerView = (AreaView *)view;
            
            centerView.hidden = NO;
            
            centerView.center = CGPointMake(fabs(centerView.relationView1.center.x - centerView.relationView2.center.x)/2 + MIN(centerView.relationView1.center.x, centerView.relationView2.center.x), fabs(centerView.relationView1.center.y - centerView.relationView2.center.y)/2 + MIN(centerView.relationView1.center.y, centerView.relationView2.center.y));
        }
    }
    
    [self resetMaskPath];
}

- (void)changeImageScale:(UIPinchGestureRecognizer *)pinch {
    
    CGFloat scale = pinch.scale;
    
    self.areaWidth = kView_W(self.areaView);
    
    self.currentScale = self.lastScale + (scale - 1);
    
    if (self.currentScale > 2) {
        
        self.currentScale = 2;
    }
    
    if (self.currentScale < 1) {
        
        self.currentScale = 1;
    }
    
    self.scrollView.zoomScale = self.currentScale;
    
    if (pinch.state == UIGestureRecognizerStateEnded) {
        
        self.lastScale = self.currentScale;
        
        [self.scrollView setContentSize:CGSizeMake(kView_W(self.areaView) + 20, kView_H(self.areaView) + 20)];
    }

    if (self.currentScale > 1) {

        self.areaView.userInteractionEnabled = self.imageView.userInteractionEnabled = NO;
    } else {

        self.areaView.userInteractionEnabled = self.imageView.userInteractionEnabled = YES;
    }
    
//    NSLog(@"缩放比例：%f\n%f",self.lastScale,self.currentScale);
}

- (void)changeAreaPointWithScale:(CGFloat)scale {
    
    CGPoint topLeft = self.topLeftAreaView.center;
    CGPoint topRight = self.topRightAreaView.center;
    CGPoint bottomLeft = self.bottomLeftAreaView.center;
    CGPoint bottomRight = self.bottomRightAreaView.center;
    
    CGPoint topCenter = self.topCenterAreaView.center;
    CGPoint leftCenter = self.leftCenterAreaView.center;
    CGPoint bottomCenter = self.bottomCenterAreaView.center;
    CGPoint rightCenter = self.rightCenterAreaView.center;
    
    self.topLeftAreaView.center = CGPointMake(topLeft.x+scale, topLeft.y+scale);
    self.topRightAreaView.center = CGPointMake(topRight.x+scale, topRight.y+scale);
    self.bottomLeftAreaView.center = CGPointMake(bottomLeft.x+scale, bottomLeft.y+scale);
    self.bottomRightAreaView.center = CGPointMake(bottomRight.x+scale, bottomRight.y+scale);
    
    self.topCenterAreaView.center = CGPointMake(topCenter.x+scale, topCenter.y+scale);
    self.leftCenterAreaView.center = CGPointMake(leftCenter.x+scale, leftCenter.y+scale);
    self.bottomCenterAreaView.center = CGPointMake(bottomCenter.x+scale, bottomCenter.y+scale);
    self.rightCenterAreaView.center = CGPointMake(rightCenter.x+scale, rightCenter.y+scale);
    
    [self resetMaskPath];
}


#pragma mark - scrollView delegate
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {

    return self.imageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {

    self.maskView.frame =
    self.areaView.frame = CGRectMake(10, 10, (kView_W(self.scrollView) - 20)*self.currentScale, (kView_H(self.scrollView) - 20)*self.currentScale);

    CGFloat areaCurrentW = kView_W(self.areaView);
    
    [self changeAreaPointWithScale:(areaCurrentW - self.areaWidth)/2];
}

#pragma mark - init UI
- (UIScrollView *)scrollView {
    
    if (!_scrollView) {
        
        _scrollView = [[UIScrollView alloc] init];
        
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        
        _scrollView.minimumZoomScale = 1;
        _scrollView.maximumZoomScale = 2;
        
        _scrollView.delegate = self;
        
        [_scrollView addGestureRecognizer:[[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(changeImageScale:)]];
    }
    
    return _scrollView;
}

- (UIImageView *)imageView {
    
    if (!_imageView) {
        
        _imageView = [[UIImageView alloc] init];
        _imageView.contentMode = UIViewContentModeScaleAspectFit;
        _imageView.userInteractionEnabled = YES;
    }
    
    return _imageView;
}

- (UIView *)maskView {
    
    if (!_maskView) {
        
        _maskView = [[UIView alloc] init];
        _maskView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.5];
        _maskView.userInteractionEnabled = NO;
    }
    
    return _maskView;
}

- (UIView *)areaView {
    
    if (!_areaView) {
        
        _areaView = [[UIView alloc] init];
        _areaView.backgroundColor = [UIColor clearColor];
        [_areaView addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(moveArea:)]];
        
        [_areaView addGestureRecognizer:[[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(changeImageScale:)]];
    }
    
    return _areaView;
}

- (AreaView *)topLeftAreaView {
    
    if (!_topLeftAreaView) {
        
        _topLeftAreaView = [[AreaView alloc] initWithFrame:CGRectMake(0, 0, areaPointWH, areaPointWH)];
        [_topLeftAreaView addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(movePoint:)]];
        _topLeftAreaView.hidden = YES;
        
        _topLeftAreaView.relationView1 = self.topCenterAreaView;
        _topLeftAreaView.relationView2 = self.leftCenterAreaView;
    }
    
    return _topLeftAreaView;
}

- (AreaView *)topRightAreaView {
    
    if (!_topRightAreaView) {
        
        _topRightAreaView = [[AreaView alloc] initWithFrame:CGRectMake(0, 0, areaPointWH, areaPointWH)];
        [_topRightAreaView addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(movePoint:)]];
        _topRightAreaView.hidden = YES;
        
        _topRightAreaView.relationView1 = self.topCenterAreaView;
        _topRightAreaView.relationView2 = self.rightCenterAreaView;
    }
    
    return _topRightAreaView;
}

- (AreaView *)bottomLeftAreaView {
    
    if (!_bottomLeftAreaView) {
        
        _bottomLeftAreaView = [[AreaView alloc] initWithFrame:CGRectMake(0, 0, areaPointWH, areaPointWH)];
        [_bottomLeftAreaView addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(movePoint:)]];
        _bottomLeftAreaView.hidden = YES;
        
        _bottomLeftAreaView.relationView1 = self.bottomCenterAreaView;
        _bottomLeftAreaView.relationView2 = self.leftCenterAreaView;
    }
    
    return _bottomLeftAreaView;
}

- (AreaView *)bottomRightAreaView {
    
    if (!_bottomRightAreaView) {
        
        _bottomRightAreaView = [[AreaView alloc] initWithFrame:CGRectMake(0, 0, areaPointWH, areaPointWH)];
        [_bottomRightAreaView addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(movePoint:)]];
        _bottomRightAreaView.hidden = YES;
        
        _bottomRightAreaView.relationView1 = self.bottomCenterAreaView;
        _bottomRightAreaView.relationView2 = self.rightCenterAreaView;
    }
    
    return _bottomRightAreaView;
}

- (AreaView *)topCenterAreaView {
    
    if (!_topCenterAreaView) {
        
        _topCenterAreaView = [[AreaView alloc] initWithFrame:CGRectMake(0, 0, areaPointWH, areaPointWH)];
        [_topCenterAreaView addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(moveCenterPoint:)]];
        _topCenterAreaView.hidden = YES;
        
        _topCenterAreaView.relationView1 = self.topLeftAreaView;
        _topCenterAreaView.relationView2 = self.topRightAreaView;
    }
    
    return _topCenterAreaView;
}

- (AreaView *)leftCenterAreaView {
    
    if (!_leftCenterAreaView) {
        
        _leftCenterAreaView = [[AreaView alloc] initWithFrame:CGRectMake(0, 0, areaPointWH, areaPointWH)];
        [_leftCenterAreaView addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(moveCenterPoint:)]];
        _leftCenterAreaView.hidden = YES;
        
        _leftCenterAreaView.relationView1 = self.topLeftAreaView;
        _leftCenterAreaView.relationView2 = self.bottomLeftAreaView;
    }
    
    return _leftCenterAreaView;
}

- (AreaView *)rightCenterAreaView {
    
    if (!_rightCenterAreaView) {
        
        _rightCenterAreaView = [[AreaView alloc] initWithFrame:CGRectMake(0, 0, areaPointWH, areaPointWH)];
        [_rightCenterAreaView addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(moveCenterPoint:)]];
        _rightCenterAreaView.hidden = YES;
        
        _rightCenterAreaView.relationView1 = self.topRightAreaView;
        _rightCenterAreaView.relationView2 = self.bottomRightAreaView;
    }
    
    return _rightCenterAreaView;
}

- (AreaView *)bottomCenterAreaView {
    
    if (!_bottomCenterAreaView) {
        
        _bottomCenterAreaView = [[AreaView alloc] initWithFrame:CGRectMake(0, 0, areaPointWH, areaPointWH)];
        [_bottomCenterAreaView addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(moveCenterPoint:)]];
        _bottomCenterAreaView.hidden = YES;
        
        _bottomCenterAreaView.relationView1 = self.bottomLeftAreaView;
        _bottomCenterAreaView.relationView2 = self.bottomRightAreaView;
    }
    
    return _bottomCenterAreaView;
}

- (CAShapeLayer *)lineLayer {
    
    if (!_lineLayer) {
        
        _lineLayer = [CAShapeLayer layer];
        _lineLayer.lineWidth = 2;
        _lineLayer.strokeColor = [UIColor clearColor].CGColor;
        _lineLayer.fillColor = [UIColor clearColor].CGColor;
    }
    
    return _lineLayer;
}

- (MagnifierView *)magnifierView {
    
    if (!_magnifierView) {
        
        _magnifierView = [[MagnifierView alloc] init];
        _magnifierView.renderView = self.window;
    }
    
    return _magnifierView;
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    // 如果View不为空，代表触摸的位置有视图拦截了这个事件
    UIView *view = [super hitTest:point withEvent:event];
    
    for (UIView *subView in self.areaView.subviews) {
        
        CGPoint myPoint = [subView convertPoint:point fromView:self];
        
        if (CGRectContainsPoint(subView.bounds, myPoint)) {
            // 返回一个拦截事件的对象，这个对象可以是self，也可以是具体的子控件
            return subView;
        }
    }
    
    return view;
}

@end







@interface AreaView ()

@end

@implementation AreaView

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        [self.layer addSublayer:self.centerLayer];
        self.backgroundColor = [UIColor clearColor];
    }
    
    return self;
}

- (CAShapeLayer *)centerLayer {
    
    if (!_centerLayer) {
        
        _centerLayer = [CAShapeLayer layer];
        _centerLayer.frame = CGRectMake(self.center.x - 5, self.center.y - 5, 10, 10);
        _centerLayer.fillColor = [UIColor whiteColor].CGColor;
        _centerLayer.strokeColor = [UIColor clearColor].CGColor;
        _centerLayer.strokeEnd = 1;
        _centerLayer.lineWidth = 2;
        
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:_centerLayer.bounds cornerRadius:5];
        _centerLayer.path = path.CGPath;
    }
    
    return _centerLayer;
}

@end



@implementation UIImage (ClipImageHandler)

// 根据path在rect范围内切割图片
- (UIImage*)clipWithPath:(UIBezierPath*)path rect:(CGRect)clipRect {
    
    @autoreleasepool {
        
        UIImage * image = [self copy];
            
        // 解决相册获取图片不是朝上的问题 - 重置为UIImageOrientationUp
        if (image.imageOrientation != UIImageOrientationUp) {
            
            UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
            [image drawInRect:(CGRect){0, 0, image.size}];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }
        
        //开始绘制图片
    //    UIGraphicsBeginImageContext(image.size);
        UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
        
        CGContextRef contextRef = UIGraphicsGetCurrentContext();
        
        UIBezierPath * clipPath = path;
        CGContextAddPath(contextRef, clipPath.CGPath);
        CGContextClosePath(contextRef);
        CGContextClip(contextRef);
        
        //坐标系转换
        //因为CGContextDrawImage会使用Quartz内的以左下角为(0,0)的坐标系
        CGContextTranslateCTM(contextRef, 0, image.size.height);
        CGContextScaleCTM(contextRef, image.scale, -image.scale);
        CGRect drawRect = CGRectMake(0, 0, image.size.width, image.size.height);
        CGContextDrawImage(contextRef, drawRect, [image CGImage]);
        //结束绘画
        UIImage *destImg = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        destImg = [destImg clipImageWithRect:clipRect];
        
        //转成png格式 会保留透明
        NSData * data = UIImageJPEGRepresentation(destImg, .5);
        UIImage * dImage = [UIImage imageWithData:data];
        
        //return destImg;
        return dImage;
    }
}

/// 根据rect裁剪图片
- (UIImage *)clipImageWithRect:(CGRect)rect{
    
    /// 裁剪的区域 - 宽高需要减去x、y，否则裁剪的图片会多出一截空白
    CGRect clipRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width - rect.origin.x, rect.size.height - rect.origin.y);
    
    CGImageRef  imageRef = CGImageCreateWithImageInRect(self.CGImage, clipRect);
    UIImage * clipImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);//很重要，不能缺少
    
    return clipImage;
}

@end
